package com.ibeeking.found.cop.b.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.cop.b.rest.service.IMsgFansMomentTaskFriendsService;
import com.ibeeking.found.cop.b.rest.service.IMsgMessageTaskSenderService;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.dos.MsgMessageTaskSenderDO;
import com.ibeeking.found.cop.service.common.query.MsgMessageTaskSenderQuery;
import com.ibeeking.found.cop.service.common.vo.MsgMessageTaskSenderVO;
import com.ibeeking.found.cop.service.mapper.MsgMessageTaskSenderMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.date.DateUtil;
import com.ibeeking.nematos.utils.json.JsonUtils;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.contact.WxCpGroupMsgTaskResult;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName MsgMessageTaskSenderServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class MsgMessageTaskSenderServiceImpl extends ServiceImpl<MsgMessageTaskSenderMapper, MsgMessageTaskSenderDO> implements IMsgMessageTaskSenderService {

    @Resource
    private MsgMessageTaskSenderMapper msgMessageTaskSenderMapper;

    @Resource
    private IMsgFansMomentTaskFriendsService msgFansMomentTaskFriendsServiceImpl;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    @Override
    public List<MsgMessageTaskSenderVO> list(MsgMessageTaskSenderQuery query) {
        List<MsgMessageTaskSenderDO> entityDOS = msgMessageTaskSenderMapper.selectList(new LambdaQueryWrapper<MsgMessageTaskSenderDO>()
                .eq(query.getId() != null, MsgMessageTaskSenderDO::getId, query.getId())
                .eq(StringUtils.isNotBlank(query.getMessageCode()), MsgMessageTaskSenderDO::getMessageCode, query.getMessageCode())
                .eq(query.getMessageId() != null, MsgMessageTaskSenderDO::getMessageId, query.getMessageId())
        );
        List<MsgMessageTaskSenderVO> entityVOS =JsonUtils.jsonToList(entityDOS, MsgMessageTaskSenderVO.class);
        return entityVOS;
    }

    @Override
    public List<MsgMessageTaskSenderVO> queryByMomentCode(String messageCode) {
        MsgMessageTaskSenderQuery query = new MsgMessageTaskSenderQuery();
        query.setMessageCode(messageCode);
        return this.getBean().list(query);
    }

    @Override
    public MsgMessageTaskSenderVO queryById(Long id) {
        MsgMessageTaskSenderDO entityDO = msgMessageTaskSenderMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        MsgMessageTaskSenderVO entityVO = BeanUtil.convertBean(entityDO, MsgMessageTaskSenderVO.class);
        return entityVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean syncMessageTaskSenderListFromWxCp(Integer tenantId, String chatType, List<String> messageCodeList){
        if(Collections3.isNotEmpty(messageCodeList)) {
            Map<String, List<String>> allValidSenderMap = new HashMap<>();

            WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId.longValue());
            WxCpConfigStorage wxCpConfigStorage = wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }
            List<MsgMessageTaskSenderDO> allNeedUpdateMessageTaskSenderDOS = new ArrayList<>();
            WxCpExternalContactService wxCpExternalContactService = wxCpService.getExternalContactService();
            if (wxCpExternalContactService == null) throw new BusinessException("获取企微服务外部联系人服务!");
            for(String messageCode: messageCodeList) {
                String nextCursor = null;
                List<MsgMessageTaskSenderDO> momentTaskSenderDOS = msgMessageTaskSenderMapper.selectList(new LambdaQueryWrapper<MsgMessageTaskSenderDO>().eq(MsgMessageTaskSenderDO::getMessageCode, messageCode));
                Map<String, MsgMessageTaskSenderDO> momentTaskSenderMap = Collections3.isNotEmpty(momentTaskSenderDOS)?momentTaskSenderDOS.stream().collect(Collectors.toMap(MsgMessageTaskSenderDO::getSenderCode, x->x, (o, n) -> n)):null;
                do {
                    try {
                        WxCpGroupMsgTaskResult wxCpGroupMsgTaskResult = wxCpExternalContactService.getGroupMsgTask(messageCode, 800, nextCursor);
                        if(wxCpGroupMsgTaskResult!=null){
                            nextCursor = wxCpGroupMsgTaskResult.getNextCursor();
                            List<WxCpGroupMsgTaskResult.ExternalContactGroupMsgTaskInfo> groupMsgTaskInfoList  = wxCpGroupMsgTaskResult.getTaskList();
                            if(Collections3.isNotEmpty(groupMsgTaskInfoList)){
                                for(WxCpGroupMsgTaskResult.ExternalContactGroupMsgTaskInfo groupMsgTaskInfo: groupMsgTaskInfoList){
                                   String senderCode =  groupMsgTaskInfo.getUserId();
                                   Integer sendStatus = groupMsgTaskInfo.getStatus();
                                   Long sendTime =  groupMsgTaskInfo.getSendTime();
                                   if(StringUtils.isNotEmpty(senderCode)){
                                       if(momentTaskSenderMap!=null && momentTaskSenderMap.containsKey(senderCode)) {
                                           MsgMessageTaskSenderDO msgMessageTaskSenderDO = momentTaskSenderMap.get(senderCode);
                                           msgMessageTaskSenderDO.setSendStatus(sendStatus);
                                           if(sendTime!=null) {
                                               msgMessageTaskSenderDO.setSendTime(DateUtil.longToLocalDateTime(sendTime));
                                           }
                                           allNeedUpdateMessageTaskSenderDOS.add(msgMessageTaskSenderDO);
                                       }
                                   }
                                }
                            }
                        }else{
                            nextCursor = null;
                        }
                    } catch (Exception e) {
                        LogUtils.error("获取客户群发消息企业发表的列表，失败原因{}", e);
                        return false;
                    }
                } while (nextCursor == null);
            }

            if(Collections3.isNotEmpty(messageCodeList)){
                msgFansMomentTaskFriendsServiceImpl.syncFansMomentTaskFriendsListFromWxCp(tenantId,messageCodeList, allValidSenderMap);
            }
            if(Collections3.isNotEmpty(allNeedUpdateMessageTaskSenderDOS)){
                this.updateBatchById(allNeedUpdateMessageTaskSenderDOS);
            }
        }
        return false;
    }

    private IMsgMessageTaskSenderService getBean(){
        return SpringBeanUtil.getBean(MsgMessageTaskSenderServiceImpl.class);
    }
}
